<template>
  <div class="container">
    <el-alert type="success">
      <p>账户ID: {{ accountId }}</p>
      <p>用户名: {{ userName }}</p>
      <p>余额: ￥{{ balance }} 元</p>
      <p>当发起出售、购买捐赠或需求后，担保状态为true</p>
      <p>当担保状态为false时，才可发起出售、购买捐赠或需求操作</p>
    </el-alert>
    <div v-if="itemList.length == 0" style="text-align: center">
      <el-alert title="查询不到数据" type="warning" />
    </div>
    <el-row v-loading="loading" :gutter="20" style="text-align: left">
      <el-col
        v-for="(val, index) in itemList"
        :key="index"
        :span="6"
        :offset="1"
      >
        <el-card v-if="val.option === true" class="item-card">
          <div slot="header" class="clearfix">
            担保状态:
            <span style="color: rgb(255, 0, 0)">{{ val.encumbrance }}</span>
          </div>
          <div class="item">
            <el-tag style="font-size = 20px" type="warning"
              >购买状态：{{
                val.sellingStatus !== undefined ? val.sellingStatus : "销售中"
              }}</el-tag
            >
            <el-button
              v-if="val.poster === accountId && val.sellingStatus === '交付中'"
              style="float: right; padding: 8px 0px"
              type="success"
              @click="updateSelling(val, 'done')"
              >确认收款</el-button
            >
            <el-button
              v-if="val.taker === accountId && val.sellingStatus === '购买中'"
              style="float: right; padding: 8px 0px"
              type="warning"
              @click="updateSelling(val, 'cancelled')"
              >取消</el-button
            >
          </div>
          <div class="item">
            <el-tag>商品ID: </el-tag>
            <span>{{ val.itemId }}</span>
          </div>
          <div class="item">
            <el-tag>发布者ID: </el-tag>
            <span>{{ val.poster }}</span>
          </div>
          <div v-if="val.taker === ''">
            <div class="item">
              <el-tag>购买者：</el-tag>
              <span>暂无</span>
            </div>
          </div>
          <div v-else>
            <div class="item">
              <el-tag>购买者ID：</el-tag>
              <span>{{ val.taker }}</span>
            </div>
          </div>
          <div class="item">
            <el-tag>商品标题: </el-tag>
            <span>{{ val.title }}</span>
          </div>
          <div class="item">
            <el-tag>商品内容: </el-tag>
            <span>{{ val.description }}</span>
          </div>
          <div v-if="val.posterImg !== ''" class="item">
            <el-tag>商品图片描述： </el-tag>
            <span>{{ val.posterImg }} </span>
          </div>
          <div class="item" type="warning">
            <el-tag>价格： </el-tag>
            <span>{{ val.price }} </span>
          </div>
          <div class="item">
            <el-tag type="warning">有效期: </el-tag>
            <span>{{ val.salePeriod }} 天</span>
          </div>
          <div
            v-if="!val.encumbrance && val.poster !== accountId"
            style="text-align: center"
          >
            <el-button type="text" @click="openSellingDialog(val)"
              >购买</el-button
            >
          </div>
          <el-rate v-if="roles[0] === 'admin'" />
          <!-- TODO:设置星星 -->
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      v-loading="loadingDialog"
      :visible.sync="dialogCreateSelling"
      :close-on-click-modal="false"
    >
      <el-form :rules="rules" label-width="100px">
        <div class="item">
          <el-tag type="danger">您将会花费 </el-tag>
          <span>{{ valItem.price }} 元</span>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="CreateSelling(valItem)"
          >立即购买</el-button
        >
        <el-button @click="dialogCreateSelling = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
// import { queryAccountList } from "@/api/account";
import { queryItem } from "@/api/item";
import { querySellingList, updateSelling } from "@/api/selling";

export default {
  name: "MyItem",
  data() {
    var checkSelling = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error("必须大于0"));
      } else {
        callback();
      }
    };
    return {
      dataList: "",
      loading: true,
      loadingDialog: false,
      itemList: [],
      sellingList: [],
      dialogCreateSelling: false,
      dialogCreateSelling: false,
      rules: {
        price: [{ validator: checkSelling, trigger: "blur" }],
      },
      accountList: [],
      valItem: {},
    };
  },
  computed: {
    ...mapGetters(["accountId", "roles", "userName", "balance"]),
  },
  created() {
    querySellingList()
      .then((response) => {
        if (response !== null) {
          this.sellingList = response;
        }
        this.loading = false;
      })
      .catch((_) => {
        this.loading = false;
      });
    queryItem()
      .then((response) => {
        if (response !== null) {
          this.itemList = response;
          this.itemList.forEach((list, idx) => {
            this.sellingList.forEach((dList, _) => {
              if (list.itemId === dList.objectOfSale) {
                console.log("the " + idx + "th item add status!");
                this.itemList[idx].createTime = dList.createTime;
                this.itemList[idx].salePeriod = dList.salePeriod;
                this.itemList[idx].sellingStatus = dList.sellingStatus;
              }
            });
          });
          // console.log(this.sellingList);
          console.log(this.itemList);
        }
        this.loading = false;
      })
      .catch((_) => {
        this.loading = false;
      });
  },
  methods: {
    updateSelling(item, type) {
      let tip = "";
      if (type === "done") {
        tip = "确认接受购买";
      } else {
        tip = "取消购买操作";
      }
      this.$confirm("是否要" + tip + "?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(() => {
          this.loading = true;
          updateSelling({
            buyer: item.taker,
            seller: item.poster,
            objectOfSale: item.itemId,
            status: type,
          })
            .then((response) => {
              this.loading = false;
              if (response !== null) {
                this.$message({
                  type: "success",
                  message: tip + "操作成功!",
                });
              } else {
                this.$message({
                  type: "error",
                  message: tip + "操作失败!",
                });
              }
              setTimeout(() => {
                window.location.reload();
              }, 1000);
            })
            .catch((_) => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.loading = false;
          this.$message({
            type: "info",
            message: "已取消" + tip,
          });
        });
    },

    change(file, fileList) {
      //将每次图片数组变化的时候，实时的进行监听，更改数组里面的图片数据
      var arr = [];
      fileList.forEach((item) => {
        arr.push(item.raw);
      });
      this.dataList = arr;
      //   console.log(arr);
    },
    openSellingDialog(item) {
      this.dialogCreateSelling = true;
      this.valItem = item;
    },
    CreateSelling(item) {
      this.$confirm("是否立即购买?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(() => {
          console.log(this.accountId);
          console.log(item.poster);
          console.log(item.itemId);
          this.loading = true;
          updateSelling({
            buyer: this.accountId,
            seller: item.poster,
            status: "addBuyer",
            objectOfSale: item.itemId,
          })
            .then((response) => {
              this.loading = false;
              if (response !== null) {
                this.$message({
                  type: "success",
                  message: "购买成功!",
                });
              } else {
                this.$message({
                  type: "error",
                  message: "购买失败!",
                });
              }
              setTimeout(() => {
                window.location.reload();
              }, 1000);
            })
            .catch((_) => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.loading = false;
          this.$message({
            type: "info",
            message: "已取消购买",
          });
        });
    },
  },
};
</script>


<style>
.container {
  width: 100%;
  text-align: center;
  min-height: 100%;
  overflow: hidden;
}
.tag {
  float: left;
}

.item {
  font-size: 14px;
  margin-bottom: 18px;
  color: #999;
}

.clearfix:before,
.clearfix:after {
  display: table;
}
.clearfix:after {
  clear: both;
}

.item-card {
  width: 280px;
  height: fit-content;
  margin: 18px;
}
</style>
